package com.kuang.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.common.utils.PageUtils;
import com.kuang.common.utils.Query;
import com.kuang.common.utils.R;
import com.kuang.gulimall.ware.dao.WareInfoDao;
import com.kuang.gulimall.ware.entity.WareInfoEntity;
import com.kuang.gulimall.ware.feign.MemberFeignService;
import com.kuang.gulimall.ware.service.WareInfoService;
import com.kuang.gulimall.ware.vo.FareVo;
import com.kuang.gulimall.ware.vo.MemberAddressVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(w->{
                w.like("name",key).or().like("address",key);
            });
        }


        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**根据收货地址计算运费
     *
     * @param addrId
     * @return
     */
    @Override
    public FareVo getFare(Long addrId) {

        FareVo fareVo = new FareVo();
        //远程查询地址
        R addr = memberFeignService.info(addrId);
        MemberAddressVo data = (MemberAddressVo) addr.getmyData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {});
        if (data!=null){
            //把手机尾号的最后一位信息变成运费
            //我这里除了新疆西藏都是15把
            if (!data.getProvince().equals("新疆")&!data.getProvince().equals("西藏")&!data.getProvince().equals("")){
                fareVo.setAddress(data);
                fareVo.setFare(new BigDecimal("15"));
                return fareVo;
            }
            else {
                fareVo.setAddress(data);
                fareVo.setFare(new BigDecimal("20"));
                return fareVo;
            }
        }
        return null;
    }

}